package lib.bone.system.listener;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.extra.pinyin.PinyinUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import lib.bone.system.domain.dto.user.UserImportDTO;
import lib.bone.system.domain.entity.SysDept;
import lib.bone.system.domain.entity.SysUser;
import lib.bone.system.service.SysDeptService;
import lib.bone.system.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

@Slf4j
public class UserImportListener extends AnalysisEventListener<UserImportDTO> {

    /**
     * 用户服务
     */
    SysUserService userService;
    /**
     * 部门服务
     */
    SysDeptService deptService;

    public UserImportListener(){}

    public UserImportListener(SysUserService userService, SysDeptService deptService){
        this.userService = userService;
        this.deptService = deptService;
    }

    @Override
    @Transactional
    public void invoke(UserImportDTO userImportDTO, AnalysisContext analysisContext) {
        Optional<SysUser> userOp = userService.findByUserName(userImportDTO.getUserName());
        if (userOp.isPresent()) {
            log.info("{},{}导入失败,存在重复数据", userImportDTO.getUserName(), userImportDTO.getNickName());
            return;
        }
        SysUser user = new SysUser();
        Optional<SysDept> deptOP = deptService.findByDeptName(userImportDTO.getDeptName());
        if (!deptOP.isPresent()) {
            log.info("{},{}导入失败,不存在对应部门{}信息", userImportDTO.getUserName(), userImportDTO.getNickName(),userImportDTO.getDeptName());
            return;
        }
        BeanUtil.copyProperties(userImportDTO,user, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        // 基础
        user.setStatus(1);
        user.setDeptId(deptOP.get().getId());
        user.setPassword("123456");
        user.setInitial(PinyinUtil.getFirstLetter(user.getNickName(),"").substring(0,1));
        userService.saveOne(user);
        log.info("{},{}导入成功", userImportDTO.getUserName(), userImportDTO.getNickName());
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        log.info("数据导入完成");
    }
}
